﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using AutoLoL.Entities;
using AutoLoL.Logic;
using AutoLoL.Logic.Factories;
using System.Data;

namespace AutoLoL.Dialogs
{
    /// <summary>
    /// Interaction logic for ItemDialog.xaml
    /// </summary>
    public partial class ItemDialog : Window
    {
        private string[] filters = null;
        private System.Timers.Timer _filterTimer;

        public Item SelectedItem { get; private set; }

        public ItemDialog(Window owner, Item item)
        {
            InitializeComponent();

            Owner = owner;

            SelectButton.IsDefault = true;
            CancelButton.IsCancel = true;

            ReadOnlyCollection<Item> items = ItemFactory.Instance.GetAll();
            ItemsDataGrid.ItemsSource = items;

            if (item != null)
            {
                ItemsDataGrid.SelectedItem = item;
            }
            else
            {
                ItemsDataGrid.SelectedIndex = 0;
            }

            ApplyFilter();
            FilterTextBox.Focus();

            _filterTimer = new System.Timers.Timer(100);
            _filterTimer.Elapsed += new ElapsedEventHandler(FilterTimer_Elapsed);
            _filterTimer.AutoReset = false;
            _filterTimer.Enabled = true;
            _filterTimer.Stop();
        }

        private void SelectButton_Click(object sender, RoutedEventArgs e)
        {
            SelectedItem = ItemsDataGrid.SelectedItem as Item;
            Close();
        }

        private void NoneButton_Click(object sender, RoutedEventArgs e)
        {
            // Ugly, but oh well =)
            SelectedItem = new Item() { Name = "None" };
            Close();
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            SelectedItem = null;
            Close();
        }

        private void ApplyFilter(Item item = null)
        {
            filters = FilterTextBox.Text.ToLower().Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);

            ICollectionView view = CollectionViewSource.GetDefaultView(ItemsDataGrid.ItemsSource);
            if (view != null)
            {
                view.Filter = FilterPredicate;

                SelectButton.IsEnabled = (ItemsDataGrid.Items.Count != 0);

                if (item != null)
                {
                    ItemsDataGrid.SelectedItem = item;
                    ItemsDataGrid.ScrollIntoView(item);
                }
                else
                {
                    ItemsDataGrid.SelectedIndex = 0;
                }
            }
        }

        private bool FilterPredicate(object obj)
        {
            if (filters == null || filters.Length == 0)
            {
                return true;
            }

            Item item = obj as Item;
            string name = item.Name.ToLower();
            foreach (string filter in filters)
            {
                if (name.Contains(filter))
                {
                    return true;
                }
            }

            return false;
        }

        private void FilterTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                ApplyFilter();
            }
        }

        private void FilterTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            Dispatcher.BeginInvoke((ThreadStart)(() =>
            {
                ApplyFilter();
            }));
        }

        private void FilterTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            _filterTimer.Stop();
            _filterTimer.Start();
        }

        private void ItemsDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                Item item = e.AddedItems[0] as Item;

                if (item != null)
                {
                    BuildsToItemsControl.ItemsSource = item.BuildsInto;
                    BuiltFromItemsControl.ItemsSource = item.BuiltFrom;
                }
            }
        }

        private void ItemImage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Image image = sender as Image;

            if (image != null)
            {
                Item item = image.DataContext as Item;

                if (item != null)
                {
                    FilterTextBox.TextChanged -= FilterTextBox_TextChanged;
                    FilterTextBox.Text = "";
                    FilterTextBox.TextChanged += FilterTextBox_TextChanged;

                    ApplyFilter(item);
                }
            }
        }

        private void ItemsDataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            e.Row.MouseDoubleClick += new MouseButtonEventHandler(Row_MouseDoubleClick);
        }

        private void ItemsDataGrid_UnloadingRow(object sender, DataGridRowEventArgs e)
        {
            e.Row.MouseDoubleClick -= new MouseButtonEventHandler(Row_MouseDoubleClick);
        }

        private void Row_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            DataGridRow row = sender as DataGridRow;
            if (row != null)
            {
                Item item = row.Item as Item;

                if (item != null)
                {
                    SelectedItem = item;
                    Close();
                }
            }
        }
    }
}
